package com.tomjun.permission.service.impl;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSONObject;
import com.tomjun.common.JsonModel;
import com.tomjun.permission.mapper.LoginDao;
import com.tomjun.permission.model.UserInfo;
import com.tomjun.permission.service.LoginService;
import com.tomjun.permission.service.PermissionService;
import com.tomjun.permission.util.CommonUtil;
import com.tomjun.permission.util.Constants;

/**
 * @author: hxy
 * @description: 登录service实现类
 * @date: 2017/10/24 11:53
 */
@Service
public class LoginServiceImpl implements LoginService {

	@Autowired
	private LoginDao loginDao;
	@Autowired
	private PermissionService permissionService;


	/**
	 * 根据用户名和密码查询对应的用户
	 */
	@Override
	public JSONObject getUser(String username, String password) {
		return loginDao.getUser(username, password);
	}

	/**
	 * 查询当前登录用户的权限等信息
	 */
	@Override
	public JsonModel<Object> getInfo() {
		JsonModel<Object> jsonModel=new JsonModel<Object>();
		//从session获取用户信息
		Session session = SecurityUtils.getSubject().getSession();
		JSONObject userInfo =  (JSONObject) session.getAttribute(Constants.SESSION_USER_INFO);
		JSONObject userPermission = permissionService.getUserPermission(userInfo.getString("username"));
		session.setAttribute(Constants.SESSION_USER_PERMISSION, userPermission);
		jsonModel.setCode(0);
		jsonModel.setMsg("success");
		jsonModel.setData(userPermission);
		return jsonModel;
	}

	/**
	 * 退出登录
	 */
	@Override
	public void logout() {
		Subject currentUser = SecurityUtils.getSubject();
		currentUser.logout();
	}

	/**
	 * 登录表单提交
	 */
	@Override
	public void authLogin(UserInfo userInfo) {
		// TODO Auto-generated method stub
		Subject currentUser = SecurityUtils.getSubject();
		UsernamePasswordToken token = new UsernamePasswordToken(userInfo.getUsername(), userInfo.getPassword());
		currentUser.login(token);
	}
}
